package com.tairan.chapter.tio.websocket.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.starter.TioWebSocketMsgHandler;

import java.util.Objects;

/**
 * @author litairan
 * @date 2019/9/26
 */
@Slf4j
public class JjwpWsMsgHandler implements TioWebSocketMsgHandler {

    /**
     * 握手时走这个方法，业务可以在这里获取cookie，request参数等
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        String clientip = httpRequest.getClientIp();
        String myname = httpRequest.getParam("name");

        Tio.bindUser(channelContext, myname);
//		channelContext.setUserid(myname);
        log.info("收到来自{}的ws握手包\r\n{}", clientip, httpRequest.toString());
        return httpResponse;
    }

    /**
     * 握手成功之后
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        int count = Tio.getAll(channelContext.getTioConfig()).size();
        String msg = "{name:'admin',message:'" + channelContext.userid + " 进来了，共【" + count + "】人在线" + "'}";
        //用tio-websocket，服务器发送到客户端的Packet都是WsResponse
        WsResponse wsResponse = WsResponse.fromText(msg, "utf-8");
        Tio.sendToAll(channelContext.getTioConfig(), wsResponse);
    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        Tio.remove(channelContext, "receive close flag");
        return null;
    }

    /**
     * 字符消息（binaryType = blob）过来后会走这个方法
     * @param wsRequest
     * @param text
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        WsSessionContext wsSessionContext = (WsSessionContext) channelContext.get();
        HttpRequest httpRequest = wsSessionContext.getHandshakeRequest();//获取websocket握手包
        JSONObject jsonObject = JSON.parseObject(text);
        if (log.isDebugEnabled()) {
            log.debug("握手包:{}", httpRequest);
        }
        // 心跳检测
        if (Objects.equals(1, jsonObject.getIntValue("type"))) {
            return null;
        }
        String from = jsonObject.getString("from");
        String to = jsonObject.getString("to");
        String msg = "{name:'" + channelContext.userid + "',message:'" + text + "'}";
        log.info(msg);
        //用tio-websocket，服务器发送到客户端的Packet都是WsResponse
        WsResponse wsResponse = WsResponse.fromText(msg, "utf-8");
        //群发
        Tio.sendToUser(channelContext.getTioConfig(), to, wsResponse);
        return null;
    }
}
